package org.example.listener;

import com.alibaba.fastjson.JSON;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.example.cache.ClientCache;
import org.example.po.Msg;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.UUID;

/**
 * @author zhangjg
 * @desc
 * @date 2023/05/07 17:17
 **/
@Component
@Slf4j
public class EventListener implements InitializingBean {

    @Autowired
    private ClientCache clientCache;

    @Autowired
    private DefaultMQProducer producer;

    /**
     * 客户端连接
     *
     * @param client
     */
    @OnConnect
    public void onConnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        UUID sessionId = client.getSessionId();
        clientCache.saveClient(userId, sessionId, client);
        log.info("建立连接,{},{}", userId, sessionId);
    }

    /**
     * 客户端断开
     *
     * @param client
     */
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        clientCache.deleteSessionClient(userId, client.getSessionId());
        log.info("关闭连接,{},{}", userId, client.getSessionId());
    }

    //消息接收入口，当接收到消息后，查找发送目标客户端，并且向该客户端发送消息，且给自己发送消息
    @OnEvent("chatevent")
    public void onEvent(SocketIOClient client, Msg msg) {
        msg.setSessionId(client.getSessionId().toString());
//        client.sendEvent("chatevent",msg);
        try {
            Message message = new Message("t11" /* Topic */,
                    "Tag_1" /* Tag */,
                    JSON.toJSONString(msg).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
            );
            SendResult sendResult = producer.send(message);
            if(sendResult.getSendStatus() != SendStatus.SEND_OK){
                log.error("onEvent sendfail");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        log.info("收到消息，sid={},userid={},msg={}", client.getSessionId(), msg.getUserId(), msg.getMessage());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        producer.start();
    }

    @Bean
    public DefaultMQProducer getProducer() {
        // 初始化一个producer并设置Producer group name
        DefaultMQProducer producer = new DefaultMQProducer("p1"); //（1）
        // 设置NameServer地址
        producer.setNamesrvAddr("192.168.10.1:9876");  //（2）
        return producer;
    }


}
